package cc.aiee.core.bean;

import java.io.Serializable;

import com.alibaba.fastjson.JSONObject;

import cc.aiee.core.enums.ErrCodeEnum;
import cc.aiee.core.kit.KitJson;
import cn.hutool.core.util.NumberUtil;
import lombok.Getter;
import lombok.Setter;

public class R<O> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Setter
	@Getter
	private String code;

	@Setter
	@Getter
	private String msg;

	@Setter
	private Boolean ok;

	@Setter
	@Getter
	private O obj;

	public R() {
		super();
	}

	public R(String code, String msg, Boolean ok, O obj) {
		super();
		this.code = code;
		this.msg = msg;
		this.ok = ok;
		this.obj = obj;
	}

	public R(ErrCodeEnum errCodeEnum) {
		this(errCodeEnum.getCode(), errCodeEnum.getMsg(), errCodeEnum.ok(), null);
	}

	public R(ErrCodeEnum errCodeEnum, Boolean ok, O obj) {
		this(errCodeEnum.getCode(), errCodeEnum.getMsg(), ok, obj);
	}

	public R(ErrCodeEnum errCodeEnum, O obj) {
		this(errCodeEnum.getCode(), errCodeEnum.getMsg(), errCodeEnum.ok(), obj);
	}

	public R(String code, String msg, O obj) {
		this(code, msg, null, obj);
	}

	public R(String code, String msg, Boolean ok) {
		this(code, msg, ok, null);
	}

	public R(String code, String msg) {
		this(code, msg, null, null);
	}

	public Boolean getOk() {
		if (ok == null && NumberUtil.isInteger(this.code)) {
			ok = (NumberUtil.parseInt(code) >= 0);
		}
		return ok;
	}

	public String toJson(boolean simple) {
		if (simple) {
			JSONObject j = new JSONObject();
			j.put("code", this.code);
			j.put("msg", this.msg);
			j.put("ok", this.ok);
			return j.toJSONString();
		}
		return KitJson.toJSONString(this);
	}

	public boolean ok() {
		return getOk();
	}

	public boolean fail() {
		return !getOk();
	}
}
